package com.yan.common.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
 * 解决中文乱码问题，读取配置文件类
 * @author hyh
 */
public class ConfUtil {
  /*  public static void main(String[] args) {
    	String path = ConfUtil.class.getResource("/properties/setting.properties").getPath();
    	String abc = ConfUtil.getInstance().getConfValue(path, "123");
    	System.out.println(abc);
	}*/
    
	private static class LazyHolder {    
	       private static final ConfUtil INSTANCE = new ConfUtil();    
	}   
	private static Properties  propertie = null;
	
	private ConfUtil(){}
	
	public static final ConfUtil getInstance(){
		return LazyHolder.INSTANCE;
	}
	/**
	 * 
	 * @param configFilePath 绝对路径
	 * @return
	 */
	@SuppressWarnings("finally")
	public Properties getProperties(String configFilePath) {  
        if(propertie == null){  
        	propertie = new Properties();  
        }  
        try {  
        	BufferedReader buff = new BufferedReader(new FileReader(configFilePath));
        	propertie.load(buff);   
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally{
        	return propertie;
        }
    }  
	/**
	 * 
	 * @param configFilePath 绝对路径
	 * @return
	 */
	@SuppressWarnings("finally")
	public Properties getProperties(InputStream inputStream) {  
        if(propertie == null){  
        	propertie = new Properties();  
        }  
        try {  
        	BufferedReader buff = new BufferedReader(new InputStreamReader(inputStream));
        	propertie.load(buff);   
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally{
        	return propertie;
        }
    }  
	/**
	 * 
	 * @param configFilePath 绝对路径 
	 * @param key
	 * @return -1 occur error.
	 */
	public String getConfValue(String configFilePath, String key) {  
        if(propertie == null){  
        	propertie = new Properties();  
        }  
        try {  
        	BufferedReader buff = new BufferedReader(new FileReader(configFilePath));
        	propertie.load(buff);
        	if(!propertie.containsKey(key)){
        		System.out.println("配置文件不含输入属性！");
        	}
        	
        	return propertie.get(key)+""; 
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
        return "-1";
    }  
	
	public String getConfValue(InputStream inputStream, String key) {  
        if(propertie == null){  
        	propertie = new Properties();  
        }  
        try {  
        	BufferedReader buff = new BufferedReader(new InputStreamReader(inputStream));
        	propertie.load(buff);
        	if(!propertie.containsKey(key)){
        		System.out.println("配置文件不含输入属性！");
        	}
        	
        	return propertie.get(key)+""; 
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
        return "-1";
    }
}
